我正在寻找设置 a 的左插图/边距,UILabel但找不到这样做的方法。标签具有背景设置,因此仅更改其原点不会起作用。最好10px在左侧插入文本。
UILabel
10px
我通过像这样子类化UILabel和覆盖来解决这个问题drawTextInRect::
drawTextInRect:
- (void)drawTextInRect:(CGRect)rect { UIEdgeInsets insets = {0, 5, 0, 5}; [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)]; }
斯威夫特 3.1:
override func drawText(in rect: CGRect) { let insets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 5) super.drawText(in: UIEdgeInsetsInsetRect(rect, insets)) }
斯威夫特 4.2.1:
override func drawText(in rect: CGRect) { let insets = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5) super.drawText(in: rect.inset(by: insets)) }
正如您可能已经收集到的,这是对改编。它比那个有两个优点:
sizeToFit